import styles from "./index.module.less";
import { useState, useEffect } from 'react';
import { Tree, Input, Spin } from 'antd';


interface Props {
	orgTree: any[];
    onChooseOrg: (keys: any, info: any) => void;
}

const { DirectoryTree } = Tree;
const { Search } = Input;

export default (props: Props) => {
    const { orgTree, onChooseOrg } = props;
    const [treeData, setTreeData] = useState(orgTree)

    useEffect(() => {
        setTreeData(orgTree)
    }, [orgTree])

    const onSearch = (searchValue: string) => {
        const result = searchTreeData(orgTree, searchValue);
        if (searchValue) {
            setTreeData(result);
        } else {
            setTreeData([]);
        }
    };
    // 获取需要展开的key
    const getExpandedKeys = (data:any, keys = []) => {
        data.forEach((node: any) => {
            if (node.children) {
                keys.push(node?.id);
                getExpandedKeys(node.children, keys);
            }
        });
        return keys;
    };

    const searchTreeData = (data: any, searchText: any) => {
        if (!searchText) return data;

        return data.map((node: any) => {
            const children = node.children ? searchTreeData(node.children, searchText) : [];
            
            // 如果当前节点匹配或者子节点有匹配，保留该节点
            const isMatch = node.name?.toLowerCase().includes(searchText.toLowerCase());
            const hasMatchingChildren = children.length > 0;

            if (isMatch || hasMatchingChildren) {
                return {
                    ...node,
                    children: hasMatchingChildren ? children : undefined,
                };
            }
            
            return null;
        })
        .filter(Boolean);
    };

    const getAllKeys = (data: any) => {
        return data.reduce((keys: any, item: any) => {
            if (item.children?.length) {
                return [...keys, item.id, ...getAllKeys(item.children)];
            }
            return [...keys, item.id];
        }, []);
    };
    
    return (
        <div className={styles.roleListBox}>
            <Search placeholder="请输入组织名称" onSearch={onSearch} className={styles.searchContainer} />
            {
                treeData && treeData.length > 0 ?
                <DirectoryTree
                    multiple
                    defaultExpandAll={true}
                    showIcon={false}
                    fieldNames={{
                        title: 'name',
                        key: 'id',
                        children: 'children',
                    }}
                    expandedKeys={getAllKeys(treeData)}
                    treeData={treeData}
                    onSelect={(keys, info) => onChooseOrg(keys, info)}
                /> : <Spin />
            }
        </div>
    )
}